package com.js.lib.endecrypt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import lombok.extern.slf4j.Slf4j;
import sun.misc.*;
/**
 * 
 * @类名: Base64Utils.java
 * @说明: 
 *
 * @author: kenny
 * @Date	2017年5月25日上午9:17:56
 * 修改记录：
 *
 * @see
 */
@Slf4j
public class Base64Utils {

	public static byte[] steamToByte(InputStream input) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = input.read(b, 0, b.length)) != -1) {                     
            baos.write(b, 0, len);
        }
        byte[] buffer =  baos.toByteArray();
        return buffer;
    }
	
	//bytetostream
	public static final InputStream byteTostream(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
    }	
	

	//转换base64字符串为文件
	public static void saveBase64strToFile(String base64str){
        if (base64str == null){
            return ;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try 
        {           
            byte[] b = decoder.decodeBuffer(base64str);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0){
                    b[i]+=256;
                }
            }            
            String imgFilePath = "c:/base.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);    
            out.write(b);
            out.flush();
            out.close();           
        } 
        catch (Exception e){
           e.printStackTrace();
        }
    }
	
	//从byte 转换为String
	@SuppressWarnings("restriction")
	public static String byteToString(byte[] keyBytes){
		BASE64Encoder encoder = new BASE64Encoder();
        String result = encoder.encode(keyBytes);
        //System.out.println(result);
        return result;
	}
	
	//String 转换为 byte
	@SuppressWarnings("restriction")
	public static byte[] stringToByte(String base64str) throws IOException{
		if (base64str == null){
            return null;
        }
		try{
			BASE64Decoder decoder = new BASE64Decoder();
	        byte[] result = decoder.decodeBuffer(base64str);
	        return result;
		}catch(IOException ie){
			log.info(">>>>>> {}",ie.toString());
			return null;
		}
        //System.out.println(result);
        
	}	
}
